import { Component, OnInit,Input,ViewChild, HostListener } from '@angular/core';
import {Router,NavigationExtras} from '@angular/router';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import { CaseService } from '../../../../../@core/service/handle-service/api/case.service';

import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';

import * as moment from 'moment'
import { UUID } from 'angular2-uuid';

@Component({
  selector: 'app-addhandle',
  templateUrl: './addhandle.component.html',
  styleUrls: ['./addhandle.component.scss']
})
  export class AddhandleComponent implements OnInit {
    @ViewChild('clickEvent') myclick;
    @ViewChild('orgTree') orgTree;
    //展开
    public isExpand:boolean = false;
    //区域数据
    public areaData: any;
    //省级联动
    public provinces:any[];
    //市级联动
    public cities:any[];
    //县级联动
    public counties:any[];
    addressDetails: any[]=[];
    private session = sessionStorage;
    expandKeys = [];                      // 默认展开的节点
    nodes = [];                           // treeSelect 组件的数据
    listOfOption = [];                    // 部门的数据
    personOptionList = [];                // 人员的数据
    public date = new Date();

    constructor(
      public clue:ClueService,
      public router:Router,
      public clueData:ClueDataService,
      private caseService: CaseService,
      private orgService: OrgService) {
        this.areaData = clueData.area;
    }
    public flag:boolean=false;
    public flags:boolean=false;
    public sortValue:any="1001";
    public providerType:any = "0";
  
    public userName = window.sessionStorage.getItem('userName');
  
    public selectValue:any=[{
      name:"法人",value:"0"
    },{
      name:"个人",value:"1"
    }];
    // 案件新增字段
    private reg = new RegExp("-","g");
    public caseList:any = {
      "cmsCase": {
        "registerCode": (UUID.UUID()).replace(this.reg, ''),                 // 登记号
        "sourceType": "1001",                // 来源分类
        "provider": {},                      // 案源提供人信息
        "partyName": "",                     // 当事人名称
        "registrant": {
          "orgId": "",
          "orgName": "",
          // "registerId": "string",
          "registerName": ""
        },
        "partyAddress": {
          "province":null,"city":null,"county":null
        },                                   // 当事人地址
        "partyAddressDetail": "",            // 当事人详细地址
        "addressDetail": "",                 // 当事人地址
        "partyPhone": "",                    // 当事人电话
        "partyOtherPhone": "",               // 当事人其他电话
        "enrollmentContent": "",             // 案源登记内容
        "enrollmentRemark": "",              // 案源登记备注
        "currentLink": "线索",                // 当前所处阶段
        "currentHandlePerson": "",           // 当前处理人
        "currentStatus": "办理中",            // 当前所处状态
        //"remark": "",                      // 备注
        "createdAt": ""                      // 登记时间
      },
      "stakerHolder": {
        "targetOrgId": null,
        "targetDeptId": null,
        "targetUserId": this.session.getItem('userId'),
        "userType":null, 
        "serial": 1,
        "stage": "线索"
      }
    }

    public caseProviderstring="";
    public addressstring="";
  
    public myDoc:any;
    public myflag:boolean;
  
    ngOnInit() {
      // 时间赋默认值
      this.caseList.cmsCase.createdAt = moment(this.date).format('YYYY-MM-DD HH:mm:ss')
      this.provinces = this.areaData;

      // 组织机构
      let nodesData = JSON.parse(this.session.getItem('areaData'));
      this.nodes = this.DataProcess(nodesData, '0', '机构');
      this.orgDefault(nodesData);
    }
    

    // 根据登录人的信息给组织机构赋默认值
    orgDefault(nodesData){
      // 获取部门
      let departments =  JSON.parse(this.session.getItem('departments'));
      // 获取机构
      let organization = JSON.parse(this.session.getItem('organizations'))[0];
      this.caseList.cmsCase.registrant.orgId = organization['orgId'];
      this.caseList.stakerHolder.targetOrgId = organization['orgId'];
      this.expandKeys = [organization['orgParentId'],organization['orgId']];
      for (let i = 0; i < departments.length; i++) {
        this.caseList.stakerHolder.targetDeptId = departments[i]['deptId'];
      } 
      this.caseList.cmsCase.registrant.registerName = this.session.getItem('realName');
    }


    //省级选择
    onProvinceChange(event){
     if(event!==null){
        this.caseList.cmsCase.partyAddress.city = null;
        this.caseList.cmsCase.partyAddress.county = null;
        this.caseList.cmsCase.partyAddressDetail = "";
        this.cities = this.provinces[0].children;
        this.addressDetails[0] = this.provinces[0].label;
        this.addressDetails[1] = this.addressDetails[2] = "";
      }else{
        this.caseList.cmsCase.partyAddress.province = null;
        this.caseList.cmsCase.partyAddress.city = null;
        this.caseList.cmsCase.partyAddress.county = null;
        this.caseList.cmsCase.partyAddressDetail = "";
        this.addressDetails[0] =this.addressDetails[1] = this.addressDetails[2] = "";
        this.cities = [];
        this.counties = [];
      }
    }
    //市级选择
    onCityChange(event){
      if(event!==null){
        this.caseList.cmsCase.partyAddress.county = null;
        this.caseList.cmsCase.partyAddressDetail = "";
        let currCity= this.cities.filter(city=>city.key==event);
        this.counties = currCity[0].children;
        this.addressDetails[1] = currCity[0].label;
        this.addressDetails[2] = "";
      }else{
        this.caseList.cmsCase.partyAddress.city = null;
        this.caseList.cmsCase.partyAddress.county = null;
        this.caseList.cmsCase.partyAddressDetail = "";
        this.addressDetails[1] = this.addressDetails[2] = "";
        this.counties = [];
      }
    }
    //县级选择
    onCountyChange(event){
      if(event!==null){
        let currCounty = this.counties.filter(county=>county.key==event);
        this.addressDetails[2] = currCounty[0].label;
      }else{
        console.log(this.caseList.cmsCase.partyAddress.county)
        this.caseList.cmsCase.partyAddress.county = null;
        this.caseList.cmsCase.partyAddressDetail = "";
        this.addressDetails[2]='';
      }
    }

    /**
     * 选择登记人 等级机关
     *  */ 
    // 将后台返回的数据处理成符合树形结构 

    DataProcess(data, parentId, type) {
      let arrayList = [];
      for(var i = 0; i < data.length; i++) {
        if (data[i]['orgTypeName'] == type && data[i]['orgParentId'] == parentId) {
          let obj = {
            'title': '', 
            'text': '',
            'value': '', 
            'key': '', 
            'parentId': '', 
            'children': []
          };
          obj.title = data[i]['orgName'] || "";
          obj.text = data[i]['orgName'] || "";
          obj.value = data[i]['orgId'] || "";
          obj.key = data[i]['orgId'] || "";
          obj.parentId = data[i]['orgParentId'] || "";
          obj.children = this.DataProcess(data, obj.value, '机构');
          if (obj.children.length <= 0) {
            obj['isLeaf'] = true;
          }
          arrayList.push(obj);
        }
      }
      return arrayList;
    }

    // 获取登记机关树中选中的节点
    getSelectedNodeList(key): void {
      let orgTreeNode = this.orgTree.getSelectedNodeList()[0]['origin'];
      this.caseList.cmsCase.registrant.orgName = orgTreeNode['text'];
      console.log(orgTreeNode);
    }

    // 去掉传参中value值为空的数据

    removeEmptyData(data: object) {
      for (let key in data) {
        if (typeof(data[key.toString()]) == 'object') {
          this.removeEmptyData(data[key]);
        } else if (!data[key.toString()]) {
          delete data[key.toString()];
        }
      }
    }

    // 选择线索来源  表单改变
    radiochang(e) {
      if(e == "1001"){
        this.caseList.cmsCase.provider={
          "jcr1":"", "ssdw1":"","jcr2":"","ssdw2":""
        }
      }else if(e == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
        this.caseList.cmsCase.provider={
          "depname":"","atten":"","telnum":"","address":""
        }
      }else if(e == "1002"){
        this.caseList.cmsCase.provider={
          "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
        }
       this.providerTypeChange(event);
      }
    }
    providerTypeChange(event):void {
      if(event=="0"){
        this.caseList.cmsCase.provider={
          "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
        }
      }else if(event=="1"){
        this.caseList.cmsCase.provider={
          "type":"1","name":"","idnum":"","telnum":"","address":"","otherinfo":""
          }
      }
    }
    // 查询地区
    findArea(areas,parentId,areaName,areaId){
      for(let i = 0; i<areas.length;i++){
         if(areas[i].areaParentId == parentId){
             areaName.push(areas[i].areaName);
             areaId.push(areas[i].areaId);
             this.findArea(areas,areas[i].areaId,areaName,areaId) 
         }
      }
      }
    // 查询地区Code  
    findAreaCode(areas,areaId){
      for(let i =0;i<areas.length;i++){
        if(areas[i].areaId == areaId){
            return areas[i].areaCode;
        }
      }
    }

    // 案件新增
    mysubmit(callback){
      let oldCaseList = new Object();
      oldCaseList = this.caseList; 
      if(this.caseList.cmsCase.createdAt){
        let datetime = moment(this.caseList.cmsCase.createdAt).format('YYYY-MM-DD HH:mm:ss')
        this.caseList.cmsCase.createdAt = datetime
      }else{
        this.caseList.cmsCase.createdAt = ''
      }

      let partyAddress = typeof(this.caseList.cmsCase.partyAddress) == 'string' ? 
                          this.caseList.cmsCase.partyAddress :
                          JSON.stringify(this.caseList.cmsCase.partyAddress);

      let provider = typeof(this.caseList.cmsCase.provider) == 'string' ?
                          this.caseList.cmsCase.provider : 
                          JSON.stringify(this.caseList.cmsCase.provider);

      this.caseList.cmsCase.partyAddress = partyAddress;
      this.caseList.cmsCase.provider = provider;
      // 获取登记组织名称
      let orgTreeNode = this.orgTree.getSelectedNodeList()[0]['origin'];
      this.caseList.cmsCase.registrant.orgName = orgTreeNode['text'];
      this.caseList.cmsCase.currentHandlePerson = this.session.getItem('userId');
      this.caseList.cmsCase.addressDetail = this.addressDetails[0] 
                                            + this.addressDetails[1] 
                                            + this.addressDetails[2]
                                            + this.caseList.cmsCase.partyAddressDetail;
      let roleInfo = JSON.parse(this.session.getItem('roles'));
      let userType:any[] = []; 
      for (let i = 0; i < roleInfo.length; i++) {
        userType.push(roleInfo[i]['roleName']);
      }

      // 新增5条当前办理人信息
      let sourceDeptId = '',sourceOrgName = '',areaName=[],areaId=[],sourceOrgId;
      let organization = JSON.parse(this.session.getItem('organizations'))[0];
      // 获取行政区划
      let areas = JSON.parse(this.session.getItem('areas'));
      sourceOrgId = organization['orgId']
      sourceOrgName = organization['orgName'];
      // 查询地区
      this.findArea(areas,'0',areaName,areaId);


      // 当前办理人名字
      this.caseList.cmsCase.currentHandlePersonName = sessionStorage.getItem('realName');
      // 当前办理人所属机构id
      this.caseList.cmsCase.currentHandleOrgId = sourceOrgId;
      // 当前办理人所属机构名称
      this.caseList.cmsCase.currentHandleOrgName = sourceOrgName;
      // 当前办理人所属地区编号
      this.caseList.cmsCase.currentHandleAreaNo = this.findAreaCode(areas,areaId[areaId.length-1]);
      // 当前办理人所属地区名称
      this.caseList.cmsCase.currentHandleAreaName = areaName[areaName.length-1];
      
      this.caseList.stakerHolder.userType = userType.join(',');
      var list:any = typeof(this.caseList) == 'string' ? JSON.stringify(this.caseList) : this.caseList;
      this.caseService.casePost(list).subscribe((data) => {
        
        this.caseList.cmsCase.provider = JSON.parse(this.caseList.cmsCase.provider)
        this.caseList.cmsCase.partyAddress = JSON.parse(this.caseList.cmsCase.partyAddress)
        if (data['rel']) {
          this.router.navigate(['/main/home/handle/previewdocument', data['data']]);
          this.flag = true
          this.flags = false;
        } else {
          this.flag = false
          this.flags = true;
        }
        this.caseList = oldCaseList;
      }, (error) => {
        this.caseList = oldCaseList;
      })
    }
  
    dodoc(e){
      if(e){
        this.myDoc=e;
        this.myflag = true;
      }else{
        this.myflag = false;
      }
    }
    
    emitFather(){
      console.log('要弹框！！！！！！！');
    }
    fun(ev){
      this.myflag = ev;
    }

    // 关闭卡片
    closeCard(){
        this.isExpand  = false;
    }
    // 切换底部card
    cardToggle($event){
      if($event){
        this.isExpand  = $event
      }
    }
  }
 